import http from 'wechat-http'

//基地址
http.baseURL = 'https://live-api.itheima.net'

//拦截器
http.intercept.request = (config) => {
  config.header = {
    Authorization: 'Bearer ' + wx.getStorageSync('token'),
    ...config.header,
  }
  return config
}

http.intercept.response = async ({ data, config }) => {
  // 正常响应返回数据
  if (data.code === 10000) {
    return data
  } else if (data.code === 401) {
    // refreshToken失效刷新token失败，跳转到登录页面
    if (config.url.includes('/refreshToken')) {
      const pages = getCurrentPages()
      const { route } = pages[pages.length - 1]
      return wx.redirectTo({
        url: '/pages/login/index?redirectUrl=/' + route,
      })
    }
    // token过期，刷新token
    const app = getApp()
    const res = await wx.http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: 'Bearer ' + wx.getStorageSync('refreshToken'),
      },
    })
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)

    config.header = {
      Authorization: 'Bearer ' + wx.getStorageSync('token'),
    }
    return http(config)
  } else {
    // 异常响应返回错误信息，不执行await后续代码
    wx.utils.toast(data.message)
    return Promise.reject(data)
  }
}
export default http
